# coding: utf-8
from sqlalchemy import BigInteger, Column, String
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.ext.declarative import declarative_base
import goodDesignImage2018Spider.dao.dbConfig as mysqlConfig

# 对象的基类
Base = mysqlConfig.get_base()
# 初始化数据库连接
engine = mysqlConfig.get_eng()
# 创建DBSession类型
DBSession = mysqlConfig.get_db_session()
metadata = Base.metadata


class FileInfo(Base):
    __tablename__ = 'file_info'
    __table_args__ = {'comment': '文件信息'}

    file_info_id = Column(BigInteger, primary_key=True, unique=True, comment='文件主键')
    file_third_network_url = Column(String(500, 'utf8mb4_general_ci'), comment='第三方网站文件url')
    file_biz_type = Column(TINYINT, comment='文件业务类型 0菜谱主图 1菜谱步骤图 2小程序用图')
    file_name = Column(String(200, 'utf8mb4_general_ci'), comment='文件名称')
    file_suffix = Column(String(100, 'utf8mb4_general_ci'), comment='文件后缀')
    file_relative_path = Column(String(200, 'utf8mb4_general_ci'), comment='文件相对路径')
    file_remark = Column(String(200, 'utf8mb4_general_ci'), comment='备注')
    file_biz_id = Column(BigInteger, comment='业务id')

    # 插入file
    @staticmethod
    def add_file_info(file):
        session = DBSession()
        session.add(file)
        session.flush()
        session.commit()
        id = file.file_info_id
        session.close()
        return id

    # 獲取需要下載的菜谱图片
    @staticmethod
    def get_need_download_img():
        session = DBSession()
        # 这里使用is None查不出, 待深究
        imgs = session.query(FileInfo).filter(FileInfo.file_relative_path == None,
                                              FileInfo.file_biz_type.in_((0, 1))).limit(10).all()
        session.close()
        return imgs

    @staticmethod
    def update_file_rel_path(file_info):
        session = DBSession()
        session.query(FileInfo).filter(FileInfo.file_info_id == file_info.file_info_id).update(
            {"file_relative_path": file_info.file_relative_path})
        session.commit()
        session.close()
